import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Workflow } from '../../workflow/schemas/workflow.schema';
import { Preset } from '../../templates/presets/schemas/preset.schema';
import { BASE_PRESETS } from '../../templates/presets/preset.config';
import mongoose from 'mongoose';

@Injectable()
export class DatabaseSeeder {
  constructor(
    @InjectModel(Workflow.name) private workflowModel: Model<Workflow>,
    @InjectModel(Preset.name) private presetModel: Model<Preset>
  ) {
    console.log('DatabaseSeeder constructed');
  }

  async seed() {
    try {
      console.log('Starting database seed...');
      console.log('Database URI:', process.env.MONGODB_URI);

      // 测试数据库连接
      const db = this.workflowModel.db;
      console.log('Database connection state:', db.readyState);

      if (mongoose.connection.readyState !== 1) {
        console.log('Connecting to database...');
        await mongoose.connect(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/commonai');
      }

      await this.seedPresets();
      await this.seedWorkflows();
      console.log('Database seed completed');
    } catch (error) {
      console.error('Error in seed:', error);
      throw error;
    }
  }

  private async seedPresets() {
    try {
      const count = await this.presetModel.countDocuments();
      console.log('Current preset count:', count);
      if (count === 0) {
        console.log('Seeding presets...');

        // 移除 id 字段，让 MongoDB 自动生成 _id
        const presetsToInsert = BASE_PRESETS.map(({ id, ...presetData }) => presetData);

        await this.presetModel.insertMany(presetsToInsert);
        console.log('Presets seeded successfully');
      } else {
        console.log('Presets already exist, skipping...');
      }
    } catch (error) {
      console.error('Error seeding presets:', error);
      throw error;
    }
  }

  private async seedWorkflows() {
    try {
      const count = await this.workflowModel.countDocuments();
      console.log('Current workflow count:', count);
      if (count === 0) {
        console.log('Seeding workflows...');
        const sampleWorkflows = [
          {
            name: '动漫人物生成',
            category: 'text2img',
            description: '生成高质量的动漫风格人物立绘',
            workflow_json: {
              nodes: {
                prompt: {
                  type: 'CLIPTextEncode',
                  inputs: {
                    text: 'masterpiece, best quality, anime style, character design'
                  }
                }
              }
            },
            param_schema: {
              basic: [
                {
                  key: 'character',
                  label: '角色描述',
                  type: 'string',
                  component: 'TextArea',
                  required: true
                }
              ],
              advanced: [
                {
                  key: 'style',
                  label: '动漫风格',
                  type: 'string',
                  component: 'Select',
                  props: {
                    options: [
                      { label: '日系', value: 'anime' },
                      { label: '赛璐璐', value: 'celluloid' }
                    ]
                  }
                }
              ]
            },
            preview_image: '/workflows/anime-character.jpg',
            created_at: new Date(),
            updated_at: new Date()
          },
          {
            name: '风景写实画',
            category: 'text2img',
            description: '生成逼真的风景照片',
            workflow_json: {
              nodes: {
                prompt: {
                  type: 'CLIPTextEncode',
                  inputs: {
                    text: 'masterpiece, best quality, photorealistic, landscape photography'
                  }
                }
              }
            },
            param_schema: {
              basic: [
                {
                  key: 'scene',
                  label: '场景描述',
                  type: 'string',
                  component: 'TextArea',
                  required: true
                }
              ],
              advanced: [
                {
                  key: 'time',
                  label: '时间',
                  type: 'string',
                  component: 'Select',
                  props: {
                    options: [
                      { label: '日出', value: 'sunrise' },
                      { label: '日落', value: 'sunset' },
                      { label: '正午', value: 'noon' },
                      { label: '夜晚', value: 'night' }
                    ]
                  }
                }
              ]
            },
            preview_image: '/workflows/landscape.jpg',
            created_at: new Date(),
            updated_at: new Date()
          },
          {
            name: '概念艺术',
            category: 'text2img',
            description: '生成科幻风格的概念设计图',
            workflow_json: {
              nodes: {
                prompt: {
                  type: 'CLIPTextEncode',
                  inputs: {
                    text: 'concept art, sci-fi, detailed, professional'
                  }
                }
              }
            },
            param_schema: {
              basic: [
                {
                  key: 'concept',
                  label: '概念描述',
                  type: 'string',
                  component: 'TextArea',
                  required: true
                }
              ]
            },
            preview_image: '/workflows/concept-art.jpg',
            created_at: new Date(),
            updated_at: new Date()
          },
          {
            name: '肖像摄影',
            category: 'text2img',
            description: '生成专业级别的人像照片',
            workflow_json: {
              nodes: {
                prompt: {
                  type: 'CLIPTextEncode',
                  inputs: {
                    text: 'professional portrait photography, studio lighting'
                  }
                }
              }
            },
            param_schema: {
              basic: [
                {
                  key: 'person',
                  label: '人物描述',
                  type: 'string',
                  component: 'TextArea',
                  required: true
                }
              ]
            },
            preview_image: '/workflows/portrait.jpg',
            created_at: new Date(),
            updated_at: new Date()
          },
          {
            name: '油画风格',
            category: 'text2img',
            description: '将照片转换为油画风格',
            workflow_json: {
              nodes: {
                prompt: {
                  type: 'CLIPTextEncode',
                  inputs: {
                    text: 'oil painting, artistic, textured'
                  }
                }
              }
            },
            param_schema: {
              basic: [
                {
                  key: 'subject',
                  label: '主题描述',
                  type: 'string',
                  component: 'TextArea',
                  required: true
                }
              ]
            },
            preview_image: '/workflows/oil-painting.jpg',
            created_at: new Date(),
            updated_at: new Date()
          },
          {
            name: '3D渲染',
            category: 'text2img',
            description: '生成3D渲染效果图',
            workflow_json: {
              nodes: {
                prompt: {
                  type: 'CLIPTextEncode',
                  inputs: {
                    text: '3d render, octane render, high detail'
                  }
                }
              }
            },
            param_schema: {
              basic: [
                {
                  key: 'object',
                  label: '物体描述',
                  type: 'string',
                  component: 'TextArea',
                  required: true
                }
              ]
            },
            preview_image: '/workflows/3d-render.jpg',
            created_at: new Date(),
            updated_at: new Date()
          },
          {
            name: '水彩画',
            category: 'text2img',
            description: '生成水彩画风格的图像',
            workflow_json: {
              nodes: {
                prompt: {
                  type: 'CLIPTextEncode',
                  inputs: {
                    text: 'watercolor painting, artistic, soft'
                  }
                }
              }
            },
            param_schema: {
              basic: [
                {
                  key: 'scene',
                  label: '场景描述',
                  type: 'string',
                  component: 'TextArea',
                  required: true
                }
              ]
            },
            preview_image: '/workflows/watercolor.jpg',
            created_at: new Date(),
            updated_at: new Date()
          },
          {
            name: '像素艺术',
            category: 'text2img',
            description: '生成复古像素风格的图像',
            workflow_json: {
              nodes: {
                prompt: {
                  type: 'CLIPTextEncode',
                  inputs: {
                    text: 'pixel art, 16-bit, retro game style'
                  }
                }
              }
            },
            param_schema: {
              basic: [
                {
                  key: 'scene',
                  label: '场景描述',
                  type: 'string',
                  component: 'TextArea',
                  required: true
                }
              ]
            },
            preview_image: '/workflows/pixel-art.jpg',
            created_at: new Date(),
            updated_at: new Date()
          },
          {
            name: '食物摄影',
            category: 'text2img',
            description: '生成诱人的美食照片',
            workflow_json: {
              nodes: {
                prompt: {
                  type: 'CLIPTextEncode',
                  inputs: {
                    text: 'food photography, professional lighting'
                  }
                }
              }
            },
            param_schema: {
              basic: [
                {
                  key: 'food',
                  label: '食物描述',
                  type: 'string',
                  component: 'TextArea',
                  required: true
                }
              ]
            },
            preview_image: '/workflows/food.jpg',
            created_at: new Date(),
            updated_at: new Date()
          },
          {
            name: '建筑设计',
            category: 'text2img',
            description: '生成建筑设计效果图',
            workflow_json: {
              nodes: {
                prompt: {
                  type: 'CLIPTextEncode',
                  inputs: {
                    text: 'architecture visualization, professional'
                  }
                }
              }
            },
            param_schema: {
              basic: [
                {
                  key: 'building',
                  label: '建筑描述',
                  type: 'string',
                  component: 'TextArea',
                  required: true
                }
              ]
            },
            preview_image: '/workflows/architecture.jpg',
            created_at: new Date(),
            updated_at: new Date()
          }
        ];

        await this.workflowModel.insertMany(sampleWorkflows);
        console.log('Workflows seeded successfully');
      } else {
        console.log('Workflows already exist, skipping...');
      }
    } catch (error) {
      console.error('Error seeding workflows:', error);
      throw error;
    }
  }
} 